package com.webserver5.core;

import com.webserver5.http.HttpServletRequest;
import com.webserver5.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File rootDir;
    private static File staticDir;
    static {
        try {
            rootDir = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    private DispatcherServlet(){}

    public static DispatcherServlet getInstance(){
        return instance;
    }
    public void service(HttpServletRequest request, HttpServletResponse respones){
        String path =request.getRequestURI();

            try {
                Method method = HandlerMapping.getMethod(path);
                if (method!=null){
                    Class cls =method.getDeclaringClass();
                    Object controller = cls.newInstance() ;
                    method.invoke(controller,request,respones);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            File file = new File(staticDir,path);
            if (file.isFile()){
                respones.setContentFile(file);
                respones.addHeader("Servre","BirdWebServer");
            }else {
                respones.setStatusCode(404);
                respones.setStatusReason("NotFound");
                file = new File(staticDir,"/root/404.html");
                respones.setContentFile(file);
            }
    }
}
